home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / site / HTTP / Headers.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  12.2 KB  |  451 lines

  1.  
  2. package HTTP::Headers;
  3.  
  4. =head1 NAME
  5.  
  6. HTTP::Headers - Class encapsulating HTTP Message headers
  7.  
  8. =head1 SYNOPSIS
  9.  
  10.  require HTTP::Headers;
  11.  $request = new HTTP::Headers;
  12.  
  13. =head1 DESCRIPTION
  14.  
  15. The C<HTTP::Headers> class encapsulates HTTP-style message headers.
  16. The headers consist of attribute-value pairs, which may be repeated,
  17. and which are printed in a particular order.
  18.  
  19. Instances of this class are usually created as member variables of the
  20. C<HTTP::Request> and C<HTTP::Response> classes, internal to the
  21. library.
  22.  
  23. =head1 METHODS
  24.  
  25. =cut
  26.  
  27.  
  28. require Carp;
  29.  
  30.  
  31.  
  32.  
  33. my @header_order = qw(
  34.    Cache-Control Connection Date Pragma Transfer-Encoding Upgrade Via
  35.  
  36.    Accept Accept-Charset Accept-Encoding Accept-Language
  37.    Authorization From Host
  38.    If-Modified-Since If-Match If-None-Match If-Range If-Unmodified-Since
  39.    Max-Forwards Proxy-Authorization Range Referer User-Agent
  40.  
  41.    Age Location Proxy-Authenticate Public Retry-After Server Vary
  42.    Warning WWW-Authenticate
  43.  
  44.    Allow Content-Base Content-Encoding Content-Language Content-Length
  45.    Content-Location Content-MD5 Content-Range Content-Type
  46.    ETag Expires Last-Modified
  47.  
  48.    Alternates Content-Version Derived-From Link URI
  49. );
  50.  
  51. my $i = 0;
  52. my %header_order;
  53. my %standard_case;
  54. for (@header_order) {
  55.     my $lc = lc $_;
  56.     $header_order{$lc} = $i++;
  57.     $standard_case{$lc} = $_;
  58. }
  59.  
  60.  
  61.  
  62. =head2 $h = new HTTP::Headers
  63.  
  64. Constructs a new C<HTTP::Headers> object.  You might pass some initial
  65. attribute-value pairs as parameters to the constructor.  I<E.g.>:
  66.  
  67.  $h = new HTTP::Headers
  68.      Date         => 'Thu, 03 Feb 1994 00:00:00 GMT',
  69.      Content_Type => 'text/html; version=3.2',
  70.      Content_Base => 'http://www.sn.no/';
  71.  
  72. =cut
  73.  
  74. sub new
  75. {
  76.     my($class) = shift;
  77.     my $self = bless {
  78.     '_header'   => { },
  79.     }, $class;
  80.  
  81.     $self->header(@_); # set up initial headers
  82.     $self;
  83. }
  84.  
  85.  
  86. =head2 $h->header($field [=> $val],...)
  87.  
  88. Get or set the value of a header.  The header field name is not case
  89. sensitive.  To make the life easier for perl users who wants to avoid
  90. quoting before the => operator, you can use '_' as a synonym for '-'
  91. in header names.
  92.  
  93. The value argument may be a scalar or a reference to a list of
  94. scalars. If the value argument is not defined, then the header is not
  95. modified.
  96.  
  97. The header() method accepts multiple ($field => $value) pairs.
  98.  
  99. The list of previous values for the last $field is returned.  Only the
  100. first header value is returned in scalar context.
  101.  
  102.  $header->header(MIME_Version => '1.0',
  103.          User_Agent   => 'My-Web-Client/0.01');
  104.  $header->header(Accept => "text/html, text/plain, image/*");
  105.  $header->header(Accept => [qw(text/html text/plain image/*)]);
  106.  @accepts = $header->header('Accept');
  107.  
  108. =cut
  109.  
  110. sub header
  111. {
  112.     my $self = shift;
  113.     my($field, $val, @old);
  114.     while (($field, $val) = splice(@_, 0, 2)) {
  115.     @old = $self->_header($field, $val);
  116.     }
  117.     wantarray ? @old : $old[0];
  118. }
  119.  
  120. sub _header
  121. {
  122.     my($self, $field, $val, $push) = @_;
  123.     $field =~ tr/_/-/;  # allow use of '_' as alternative to '-' in fields
  124.  
  125.  
  126.     Carp::croak('Need a field name') unless defined $field;
  127.     Carp::croak('Too many parameters') if @_ > 4;
  128.  
  129.     my $lc_field = lc $field;
  130.     unless(defined $standard_case{$lc_field}) {
  131.     $field =~ s/\b(\w)/\u$1/g;
  132.     $standard_case{$lc_field} = $field;
  133.     }
  134.  
  135.     my $this_header = \@{$self->{'_header'}{$lc_field}};
  136.  
  137.     my @old = ();
  138.     if (!$push && defined $this_header) {
  139.     @old = @$this_header;  # save it so we can return it
  140.     }
  141.     if (defined $val) {
  142.     @$this_header = () unless $push;
  143.     if (!ref($val)) {
  144.         push(@$this_header, $val);
  145.     } elsif (ref($val) eq 'ARRAY') {
  146.         push(@$this_header, @$val);
  147.     } else {
  148.         Carp::croak("Unexpected field value $val");
  149.     }
  150.     }
  151.     @old;
  152. }
  153.  
  154.  
  155. sub _header_cmp
  156. {
  157.     $header_order{$a} = 999 unless defined $header_order{$a};
  158.     $header_order{$b} = 999 unless defined $header_order{$b};
  159.  
  160.     $header_order{$a} <=> $header_order{$b} || $a cmp $b;
  161. }
  162.  
  163.  
  164. =head2 $h->scan(\&doit)
  165.  
  166. Apply a subroutine to each header in turn.  The callback routine is
  167. called with two parameters; the name of the field and a single value.
  168. If the header has more than one value, then the routine is called once
  169. for each value.  The field name passed to the callback routine has
  170. case as suggested by HTTP Spec, and the headers will be visited in the
  171. recommended "Good Practice" order.
  172.  
  173. =cut
  174.  
  175. sub scan
  176. {
  177.     my($self, $sub) = @_;
  178.     my $field;
  179.     foreach $field (sort _header_cmp keys %{$self->{'_header'}} ) {
  180.     my $list = $self->{'_header'}{$field};
  181.     if (defined $list) {
  182.         my $val;
  183.         for $val (@$list) {
  184.         &$sub($standard_case{$field} || $field, $val);
  185.         }
  186.     }
  187.     }
  188. }
  189.  
  190.  
  191. =head2 $h->as_string([$endl])
  192.  
  193. Return the header fields as a formatted MIME header.  Since it
  194. internally uses the C<scan()> method to build the string, the result
  195. will use case as suggested by HTTP Spec, and it will follow
  196. recommended "Good Practice" of ordering the header fieds.  Long header
  197. values are not folded. 
  198.  
  199. The optional parameter specifies the line ending sequence to use.  The
  200. default is C<"\n">.  Embedded "\n" characters in the header will be
  201. substitued with this line ending sequence.
  202.  
  203. =cut
  204.  
  205. sub as_string
  206. {
  207.     my($self, $endl) = @_;
  208.     $endl = "\n" unless defined $endl;
  209.  
  210.     my @result = ();
  211.     $self->scan(sub {
  212.     my($field, $val) = @_;
  213.     if ($val =~ /\n/) {
  214.         $val =~ s/\s+$//;          # trailing newlines and space must go
  215.         $val =~ s/\n\n+/\n/g;      # no empty lines
  216.         $val =~ s/\n([^\040\t])/\n $1/g;  # intial space for continuation
  217.         $val =~ s/\n/$endl/g;      # substitute with requested line ending
  218.     }
  219.     push(@result, "$field: $val");
  220.     });
  221.  
  222.     join($endl, @result, '');
  223. }
  224.  
  225.  
  226.  
  227.  
  228. =head2 $h->push_header($field, $val)
  229.  
  230. Add a new field value of the specified header.  The header field name
  231. is not case sensitive.  The field need not already have a
  232. value. Previous values for the same field are retained.  The argument
  233. may be a scalar or a reference to a list of scalars.
  234.  
  235.  $header->push_header(Accept => 'image/jpeg');
  236.  
  237. =head2 $h->remove_header($field,...)
  238.  
  239. This function removes the headers with the specified names.
  240.  
  241. =head2 $h->clone
  242.  
  243. Returns a copy of this HTTP::Headers object.
  244.  
  245. =head1 CONVENIENCE METHODS
  246.  
  247. The most frequently used headers can also be accessed through the
  248. following convenience methods.  These methods can both be used to read
  249. and to set the value of a header.  The header value is set if you pass
  250. an argument to the method.  The old header value is always returned.
  251.  
  252. Methods that deal with dates/times always convert their value to system
  253. time (seconds since Jan 1, 1970) and they also expect this kind of
  254. value when the header value is set.
  255.  
  256. =head2 $h->date
  257.  
  258. This header represents the date and time at which the message was
  259. originated. I<E.g.>:
  260.  
  261.   $h->date(time);  # set current date
  262.  
  263. =head2 $h->expires
  264.  
  265. This header gives the date and time after which the entity should be
  266. considered stale.
  267.  
  268. =head2 $h->if_modified_since
  269.  
  270. This header is used to make a request conditional.  If the requested
  271. resource has not been modified since the time specified in this field,
  272. then the server will return a C<"304 Not Modified"> response instead of
  273. the document itself.
  274.  
  275. =head2 $h->last_modified
  276.  
  277. This header indicates the date and time at which the resource was last
  278. modified. I<E.g.>:
  279.  
  280.   if ($h->last_modified < time - 60*60) {
  281.     ...
  282.   }
  283.  
  284. =head2 $h->content_type
  285.  
  286. The Content-Type header field indicates the media type of the message
  287. content. I<E.g.>:
  288.  
  289.   $h->content_type('text/html');
  290.  
  291. The value returned will be converted to lower case, and potential
  292. parameters will be chopped off and returned as a separate value if in
  293. an array context.  This makes it safe to do the following:
  294.  
  295.   if ($h->content_type eq 'text/html') {
  296.      ...
  297.   }
  298.  
  299. =head2 $h->content_encoding
  300.  
  301. The Content-Encoding header field is used as a modifier to the
  302. media type.  When present, its value indicates what additional
  303. encoding mechanism has been applied to the resource.
  304.  
  305. =head2 $h->content_length
  306.  
  307. A decimal number indicating the size in bytes of the message content.
  308.  
  309. =head2 $h->title
  310.  
  311. The title of the document.  In libwww-perl this header will be
  312. initialized automatically from the E<lt>TITLE>...E<lt>/TITLE> element
  313. of HTML documents.  I<This header is no longer part of the HTTP
  314. standard.>
  315.  
  316. =head2 $h->user_agent
  317.  
  318. This header field is used in request messages and contains information
  319. about the user agent originating the request.  I<E.g.>:
  320.  
  321.   $h->user_agent('Mozilla/1.2');
  322.  
  323. =head2 $h->server
  324.  
  325. The server header field contains information about the software being
  326. used by the originating server program handling the request.
  327.  
  328. =head2 $h->from
  329.  
  330. This header should contain an Internet e-mail address for the human
  331. user who controls the requesting user agent.  The address should be
  332. machine-usable, as defined by RFC822.  E.g.:
  333.  
  334.   $h->from('Gisle Aas <aas@sn.no>');
  335.  
  336. =head2 $h->referer
  337.  
  338. Used to specify the address (URI) of the document from which the
  339. requested resouce address was obtained.
  340.  
  341. =head2 $h->www_authenticate
  342.  
  343. This header must be included as part of a "401 Unauthorized" response.
  344. The field value consist of a challenge that indicates the
  345. authentication scheme and parameters applicable to the requested URI.
  346.  
  347. =head2 $h->authorization
  348.  
  349. A user agent that wishes to authenticate itself with a server, may do
  350. so by including this header.
  351.  
  352. =head2 $h->authorization_basic
  353.  
  354. This method is used to get or set an authorization header that use the
  355. "Basic Authentication Scheme".  In array context it will return two
  356. values; the user name and the password.  In scalar context it will
  357. return I<"uname:password"> as a single string value.
  358.  
  359. When used to set the header value, it expects two arguments.  I<E.g.>:
  360.  
  361.   $h->authorization_basic($uname, $password);
  362.  
  363. =cut
  364.  
  365. 1;
  366.  
  367.  
  368. sub clone
  369. {
  370.     my $self = shift;
  371.     my $clone = new HTTP::Headers;
  372.     $self->scan(sub { $clone->push_header(@_);} );
  373.     $clone;
  374. }
  375.  
  376. sub push_header
  377. {
  378.     Carp::croak('Usage: $h->push_header($field, $val)') if @_ != 3;
  379.     shift->_header(@_, 'PUSH');
  380. }
  381.  
  382.  
  383. sub remove_header
  384. {
  385.     my($self, @fields) = @_;
  386.     my $field;
  387.     foreach $field (@fields) {
  388.     $field =~ tr/_/-/;
  389.     delete $self->{'_header'}{lc $field};
  390.     }
  391. }
  392.  
  393.  
  394. sub _date_header
  395. {
  396.     require HTTP::Date;
  397.     my($self, $header, $time) = @_;
  398.     my($old) = $self->_header($header);
  399.     if (defined $time) {
  400.     $self->_header($header, HTTP::Date::time2str($time));
  401.     }
  402.     HTTP::Date::str2time($old);
  403. }
  404.  
  405. sub date              { shift->_date_header('Date',              @_); }
  406. sub expires           { shift->_date_header('Expires',           @_); }
  407. sub if_modified_since { shift->_date_header('If-Modified-Since', @_); }
  408. sub last_modified     { shift->_date_header('Last-Modified',     @_); }
  409.  
  410. sub client_date       { shift->_date_header('Client-Date',       @_); }
  411.  
  412.  
  413. sub content_type      {
  414.   my $ct = (shift->_header('Content-Type', @_))[0];
  415.   return '' unless defined $ct;
  416.   my @ct = split(/\s*;\s*/, lc($ct));
  417.   wantarray ? @ct : $ct[0];
  418. }
  419.  
  420. sub title             { (shift->_header('Title',            @_))[0] }
  421. sub content_encoding  { (shift->_header('Content-Encoding', @_))[0] }
  422. sub content_length    { (shift->_header('Content-Length',   @_))[0] }
  423.  
  424. sub user_agent        { (shift->_header('User-Agent',       @_))[0] }
  425. sub server            { (shift->_header('Server',           @_))[0] }
  426.  
  427. sub from              { (shift->_header('From',             @_))[0] }
  428. sub referer           { (shift->_header('Referer',          @_))[0] }
  429.  
  430. sub www_authenticate  { (shift->_header('WWW-Authenticate', @_))[0] }
  431. sub authorization     { (shift->_header('Authorization',    @_))[0] }
  432.  
  433. sub authorization_basic {
  434.     require MIME::Base64;
  435.     my($self, $user, $passwd) = @_;
  436.     my($old) = $self->_header('Authorization');
  437.     if (defined $user) {
  438.     $passwd = '' unless defined $passwd;
  439.     $self->_header('Authorization',
  440.                'Basic ' . MIME::Base64::encode("$user:$passwd", ''));
  441.     }
  442.     if (defined $old && $old =~ s/^\s*Basic\s+//) {
  443.     my $val = MIME::Base64::decode($old);
  444.     return $val unless wantarray;
  445.     return split(/:/, $val, 2);
  446.     }
  447.     undef;
  448. }
  449.  
  450. 1;
  451.